package com.zbs.framework.dao.utils;

import com.zbs.framework.dao.passport.base.repository.MNAccountRepository;
import com.zbs.framework.dao.passport.entity.MNAccount;
import com.zbs.framework.dao.passport.entity.MNNormal;
import com.zbs.framework.dao.security.service.SecurityPermissionService;
import com.zbs.framework.dao.user.entity.BaseUserInfo;
import com.zbs.framework.dao.user.entity.MNBaseUser;
import com.zbs.framework.dao.user.repository.UserRoleRepository;
import com.zbs.framework.security.service.TokenLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: Zbs
 * @createTime: 2021/2/25 12:11
 * 这个可以重写
 */
@Slf4j
@Component
public class SecurityUserUtils {

    @Autowired
    private MNAccountRepository mnAccountRepository;
    @Autowired
    private SecurityPermissionService securityPermissionService;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private TokenLoginService tokenLoginService;


    public Map<String, Object> returnSecurityUser(MNBaseUser baseUser, MNNormal accNormal, String entryType, Map<String, Object> otherParameters) {
        return this.returnSecurityUser(baseUser, null, accNormal, entryType, otherParameters);
    }

    public Map<String, Object> returnSecurityUser(MNBaseUser baseUser, String pwd, MNNormal accNormal, String entryType, Map<String, Object> otherParameters) {
        //用户基本信息,角色id
        final Integer[] roleIds = userRoleRepository.findRoleIds(baseUser.getId());
        //查询角色权限 Permission
        List<String> permissionValueList = this.securityPermissionService.getUserAllPermissionByUserId(baseUser.getId());
        MNAccount byUuid = this.mnAccountRepository.findById(accNormal.getAcctUuid()).orElse(new MNAccount(0));
        boolean isEnabled = byUuid.getEnabled().equals(1);
        //交给Security维护
        return this.tokenLoginService.login(baseUser.getId(), accNormal.getUsername(), accNormal.getPwd(), pwd, entryType, baseUser.getUserType(), permissionValueList, new BaseUserInfo(baseUser, roleIds), otherParameters, isEnabled);
    }
}
